package com.tjnu.baiyi.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.tjnu.baiyi.entity.TbMessage;

@Repository("tbMessageDao")
@Transactional
public class TbMessageDAO {
	@Autowired
	@Qualifier("sessionFactory")
	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	protected void initDao() {
		// do nothing
	}

	public void save(TbMessage transientInstance) {
		try {
			getCurrentSession().save(transientInstance);
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public void delete(TbMessage persistentInstance) {
		try {
			getCurrentSession().delete(persistentInstance);
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public TbMessage findById(java.lang.Integer id) {
		try {
			TbMessage instance = (TbMessage) getCurrentSession().get(
					TbMessage.class, id);
			return instance;
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public List findByExample(TbMessage instance) {
		try {
			List results = getCurrentSession().createCriteria(TbMessage.class)
					.add(Example.create(instance)).list();
			return results;
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		try {
			String queryString = "from TbMessage as model where model."
					+ propertyName + "= ?";
			Query queryObject = getCurrentSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public List findAll() {
		try {
			String queryString = "from TbMessage";
			Query queryObject = getCurrentSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			throw re;
		}
	}

	// 根据接收留言者的id查询留言
	public List<TbMessage> findAllByUserId(Integer userId) {
		try {
			String queryString = "FROM TbMessage WHERE tbUserByReceiptMessageId.userId=? ORDER BY messageTime DESC";
			Query queryObject = getCurrentSession().createQuery(queryString)
					.setInteger(0, userId);
			return queryObject.list();
		} catch (RuntimeException re) {
			throw re;
		}
	}
}